import {Injectable} from '@nestjs/common';
import {InjectRepository} from '@nestjs/typeorm';
import {AccountEntity} from '../../entities/account.entity';
import {MutationRes} from 'src/modules/shared/vo/mutation.res';
import {Repository} from 'typeorm';
import {ModifyAccountInput} from '../../resolvers/dto/modifyAccount.input';


@Injectable()
export class AccountService {
    constructor(
        @InjectRepository(AccountEntity)
        private readonly accountRepository: Repository<AccountEntity>,
    ) {
    }

    async accountList() {
        return await this.accountRepository.find();
    }

    async account(id: number) {
        return await this.accountRepository.findOne(id);
    }

    async createAccount(username: string, password: string) {
        const account = this.accountRepository.create({username, password});
        await this.accountRepository.save(account)
        return {
            code: 0,
            message: "创建成功"
        }
    }

    async modifyAccountById(id: number, modifyAccountInput: ModifyAccountInput): Promise<MutationRes> {
        const {raw: {affectedRows}} = await this.accountRepository.update(id, {...modifyAccountInput}); //{data} 会报错, 所以要 {...data}
        if (affectedRows) {
            return {
                code: 0,
                message: '修改成功',
            }
        } else {
            return {
                code: 1,
                message: '修改失败',
            }
        }
    }

    async deleteAccountById(id: number) {
        console.log("delete ---->", id);
        const {raw: {affectedRows}} = await this.accountRepository.softDelete(id);
        if (affectedRows) {
            return {
                code: 0,
                message: '删除成功',
            }
        } else {
            return {
                code: 1,
                message: '删除成功',
            }
        }
    }
}
